import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';

import '../controllers/device_detail_controller.dart';

/// 默认主要内容组件（功能按钮 + 云台控制）
///
/// 使用示例：
/// ```dart
/// // 在设备详情页面中使用
/// Widget _buildDefaultMainContent() {
///   return DefaultMainContentWidget();
/// }
///
/// // 在其他页面中独立使用（需要确保controller已初始化）
/// class SomeOtherPage extends GetView<DeviceDetailController> {
///   @override
///   Widget build(BuildContext context) {
///     return Scaffold(
///       body: DefaultMainContentWidget(),
///     );
///   }
/// }
/// ```
class DefaultMainContentWidget extends GetView<DeviceDetailController> {
  DefaultMainContentWidget({super.key});

  // 跟踪当前按压的方向
  final RxString _pressedDirection = ''.obs;

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 功能按钮区
          _buildFunctionButtons(),
          // 云台控制区
          Obx(() => _buildPTZControl()),

          // 底部间距
          SizedBox(height: 20.h),
        ],
      ),
    );
  }

  // 功能按钮区
  Widget _buildFunctionButtons() {
    return Center(
      child: Container(
        width: 710.w, // 指定宽度710px
        height: 150.h, // 指定高度150px
        margin: EdgeInsets.only(top: 10),
        decoration: BoxDecoration(
          color: const Color(0xFFFFFFFF), // 白色背景
          borderRadius: BorderRadius.circular(20.r), // 20px圆角
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.1),
              offset: const Offset(0, 2),
              blurRadius: 10,
            ),
          ],
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Obx(
              () => _buildFunctionButton(
                iconPath:
                    controller.isTalking.value
                        ? 'assets/images/device_detail/结束通话.png'
                        : 'assets/images/device_detail/talk.png',
                label: controller.isTalking.value ? '结束通话' : '对话',
                onTap: controller.startTalk,
                isLoading: controller.isConnectingTalk.value,
              ),
            ),
            // _buildFunctionButton(
            //   iconPath: 'assets/images/device_detail/screenshot.png',
            //   label: '截图',
            //   onTap: controller.takeScreenshot,
            // ),
            _buildFunctionButton(
              iconPath: 'assets/images/device_detail/capture.png',
              label: '抓拍',
              onTap: controller.captureImage,
            ),
            Obx(
              () => _buildFunctionButton(
                iconPath:
                    controller.isRecording.value
                        ? 'assets/images/device_detail/结束录像.png'
                        : 'assets/images/device_detail/record.png',
                label: controller.isRecording.value ? '结束录像' : '录像',
                onTap: controller.startRecording,
                isLoading:
                    controller.isStartingRecord.value ||
                    controller.isStoppingRecord.value,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 功能按钮
  Widget _buildFunctionButton({
    required String iconPath,
    required String label,
    required VoidCallback onTap,
    bool isLoading = false,
  }) {
    return GestureDetector(
      onTap: isLoading ? null : onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 使用图片而不是图标
          Container(
            width: 40,
            height: 40,
            child:
                isLoading
                    ? Padding(
                      padding: EdgeInsets.all(8.w),
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(
                          Color(0xFF047FF7),
                        ),
                      ),
                    )
                    : Padding(
                      padding: EdgeInsets.all(8.w),
                      child: Image.asset(iconPath, fit: BoxFit.contain),
                    ),
          ),
          SizedBox(height: 8.h),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color:
                  isLoading ? const Color(0xFF999999) : const Color(0xFF666666),
            ),
          ),
        ],
      ),
    );
  }

  // 云台控制区
  Widget _buildPTZControl() {
    // 判断是否支持云台操作：0、3、4不支持，其他支持
    final ptzType = controller.channelDetail.value?['ptzType']?.toString();
    final ptzTypeInt = int.tryParse(ptzType ?? '') ?? 0;
    final isPTZSupported =
        !(ptzTypeInt == 0 || ptzTypeInt == 3 || ptzTypeInt == 4);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 40.w, vertical: 30.h),
      child: Column(
        children: [
          // 云台控制面板
          Container(
            width: 400.w,
            height: 400.h,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 控制台背景图片 - 根据云台支持状态和按压状态决定显示
                Obx(() {
                  String backgroundImage;
                  final pressedDirection = _pressedDirection.value;
                  if (!isPTZSupported) {
                    backgroundImage =
                        'assets/images/device_detail/control_panel_no.png';
                  } else if (pressedDirection.isNotEmpty) {
                    // 根据按压方向显示对应的背景图
                    switch (pressedDirection) {
                      case '向上':
                        backgroundImage = 'assets/images/device/向上.png';
                        break;
                      case '向下':
                        backgroundImage = 'assets/images/device/向下.png';
                        break;
                      case '向左':
                        backgroundImage = 'assets/images/device/向左.png';
                        break;
                      case '向右':
                        backgroundImage = 'assets/images/device/向右.png';
                        break;
                      default:
                        backgroundImage =
                            'assets/images/device_detail/control_panel.png';
                    }
                  } else {
                    backgroundImage =
                        'assets/images/device_detail/control_panel.png';
                  }

                  return Image.asset(
                    backgroundImage,
                    width: 400.w,
                    height: 400.h,
                    fit: BoxFit.cover,
                  );
                }),

                if (isPTZSupported)
                  Positioned(
                    top: 30.h,
                    child: Opacity(
                      opacity: 0,
                      child: _buildPTZArrowLongPress(
                        Icons.keyboard_arrow_up,
                        '向上',
                      ),
                    ),
                  ),

                if (isPTZSupported)
                  Positioned(
                    bottom: 30.h,
                    child: Opacity(
                      opacity: 0,
                      child: _buildPTZArrowLongPress(
                        Icons.keyboard_arrow_down,
                        '向下',
                      ),
                    ),
                  ),

                if (isPTZSupported)
                  Positioned(
                    left: 30.w,
                    child: Opacity(
                      opacity: 0,
                      child: _buildPTZArrowLongPress(
                        Icons.keyboard_arrow_left,
                        '向左',
                      ),
                    ),
                  ),

                if (isPTZSupported)
                  Positioned(
                    right: 30.w,
                    child: Opacity(
                      opacity: 0,
                      child: _buildPTZArrowLongPress(
                        Icons.keyboard_arrow_right,
                        '向右',
                      ),
                    ),
                  ),
              ],
            ),
          ),
          if (!isPTZSupported)
            Text(
              "暂无云台，不可操作",
              style: TextStyle(color: Colors.grey, fontSize: 16),
            ),
        ],
      ),
    );
  }

  // 云台箭头按钮 - 支持短按和长按
  Widget _buildPTZArrowLongPress(IconData icon, String direction) {
    return GestureDetector(
      onTap: () {
        // ✅ 检查设备是否离线
        if (controller.isDeviceOffline) {
          BotToast.showText(text: '设备已离线');
          return;
        }
        // 短按：开始云台控制，延迟后自动停止
        _pressedDirection.value = direction;
        controller.startPTZControl(direction);

        // 延迟1秒后自动停止
        Future.delayed(const Duration(seconds: 1), () {
          if (_pressedDirection.value == direction) {
            _pressedDirection.value = '';
            controller.stopPTZControl();
          }
        });
      },
      onLongPressStart: (_) {
        // ✅ 检查设备是否离线
        if (controller.isDeviceOffline) {
          BotToast.showText(text: '设备已离线');
          return;
        }
        // 长按：开始云台控制
        _pressedDirection.value = direction;
        controller.startPTZControl(direction);
      },
      onLongPressEnd: (_) {
        // 长按结束：停止云台控制
        _pressedDirection.value = '';
        controller.stopPTZControl();
      },
      child: Container(
        width: 80.w,
        height: 80.h,
        decoration: BoxDecoration(
          color: Colors.white.withValues(alpha: 0.9),
          shape: BoxShape.circle,
          border: Border.all(color: const Color(0xFF047FF7), width: 2.w),
          boxShadow: [
            BoxShadow(
              color: const Color(0xFF047FF7).withValues(alpha: 0.3),
              offset: const Offset(0, 4),
              blurRadius: 12,
            ),
          ],
        ),
        child: Icon(icon, size: 36.w, color: const Color(0xFF047FF7)),
      ),
    );
  }
}
